using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.Reflection;
using  Microsoft.SharePoint.UserCode;

namespace Com.CodePlex.SPC3.DatabaseProxy {

    //note: need to restart sandbox code service after deploy

    [Guid("aae6dee6-b6cf-42be-918a-c5dbc7b91b9a")]
    public class DefaultEventReceiver : SPFeatureReceiver {

        public override void FeatureActivated(SPFeatureReceiverProperties properties) {
            SPUserCodeService ucService = SPUserCodeService.Local;
            string assemblyName = Assembly.GetExecutingAssembly().FullName;
            ucService.ProxyOperationTypes.Add(new SPProxyOperationType(assemblyName, typeof(SqlCommandProxyOperation).FullName));
            ucService.ProxyOperationTypes.Add(new SPProxyOperationType(assemblyName, typeof(SqlDataReaderProxyOperation).FullName));
            ucService.Update();
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties) {
            SPUserCodeService ucService = SPUserCodeService.Local;
            string assemblyName = Assembly.GetExecutingAssembly().FullName;
            List<SPProxyOperationType> deletes = new List<SPProxyOperationType>();
            foreach (SPProxyOperationType proxyOperationType in ucService.ProxyOperationTypes) {
                if (proxyOperationType.AssemblyName == assemblyName) {
                    if (proxyOperationType.TypeName == typeof(SqlCommandProxyOperation).FullName ||
                        proxyOperationType.TypeName == typeof(SqlDataReaderProxyOperation).FullName) {
                            deletes.Add(proxyOperationType);
                    }
                }
            }
            deletes.ForEach(delegate(SPProxyOperationType proxyOperationType) {
                ucService.ProxyOperationTypes.Remove(proxyOperationType);        
            });
            ucService.Update();
        }
    }
}
